﻿using System.IO;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;

namespace PhiStore.Experiments.Compression
{
    class Zip
    {
        public static Stream Compress(byte[] input, int bufferSize)
        {
            MemoryStream output = new MemoryStream();

            ZipOutputStream compressor = new ZipOutputStream(output);

            ZipEntry entry = new ZipEntry("dummy");
            entry.Size = input.Length;

            compressor.PutNextEntry(entry);

            for (int i = 0; i < input.Length; i += bufferSize)
            {
                int length = (int)(i + bufferSize > input.Length ? input.Length - i : bufferSize);

                compressor.Write(input, i, length);
            }

            compressor.CloseEntry();
            compressor.Finish();
            return output;
        }

        public static Stream Decompress(Stream input, int bufferSize)
        {
            MemoryStream output = new MemoryStream();
            input.Position = 0;

            ZipInputStream decompressor = new ZipInputStream(input);

            decompressor.GetNextEntry();

            byte[] buffer = new byte[bufferSize];
            StreamUtils.Copy(decompressor, output, buffer);

            return output;
        }
    }
}
